<template>
  <div class="page">
    <div class="weui-cells">
      <template v-if="resultList.length">
      <div class="weui-cell" v-for="(item,index) in resultList">
        <div class="weui-cell__hd">
          <img class="s_pic" :src="item.merchantDef.logoImage" mode="widthFix">
        </div>
        <div class="weui-cell__bd">
          <div class="s_info">
            <div>预约门店：{{item.merchantDef.merchantName}}</div>
            <div>预约技师：{{item.stuff.name?item.stuff.name:'无'}}</div>
            <div>预约时间：{{item.reserveTime}}</div>
            <div>预约状态：{{item.statusLabel}}</div>
            <div class="btngroup" v-if="item.status==0||item.status==1">
              <a @click="cancle(item)">取消预约</a>
              <a @click="changeTime(item)">修改时间</a>
            </div>
          </div>
        </div>
      </div>
      </template>
        <div v-if="!resultList.length" class="weui-cell" style="display: flex;justify-content: center;">
          暂无更多数据
          </div>
    </div>
    <!--    选择时间-->
    <div v-if="timeShow" class="getTIme">
      <div class="weui-mask" @click="close"></div>
      <div class="weui-dialog dialog_bot">
        <div class="weui-dialog__hd dialog_bot_title" >
          <span>选择预约时间</span>
          <div class="close" @click="close">×</div>
        </div>
        <div class="weui-dialog__bd weui-flex dialog_bot_con">
          <div class="date">
            <ul>
              <template v-if="dateList.length">
                <li v-for="(item,index) in dateList" :key="index" :class="{current:item.isCurrent}" @click="changeDate(item)">{{item.date}}</li>
              </template>


            </ul>
          </div>
          <div class="time weui-flex__item" style="height: 210px;overflow: auto">
            <template v-if="dateMinList.length">
              <div class="weui-flex" v-for="(item,i) in dateMinList" :key="i" :class="{ current:item.isClick}">
                <!-- <div class="weui-flex__item">{{item.label}}</div> -->
                <!--      <div> -->
                <!--                    <input type="radio" v-model="item.isClick" color="#FF787E"  @click="onChange(item)">-->
                <!--  <van-radio-group :value="isClick" @change="handleFruitChange">
                    <van-radio :name="item.label">{{item.label}}</van-radio>
                  </van-radio-group> -->
                <i-radio-group :current="isClick" class="radio-group" v-if="item.isYuYue"  @change="handleFruitChange">
                  <i-radio :value="item.label" position="right" >
                  </i-radio>
                </i-radio-group>
                <p
                  style="height: 48px; color: #FF787E;line-height: 48px;box-sizing: border-box;padding:12px 15px;display: flex;justify-content: space-between;width: 100%;align-items: center;"
                  v-if="!item.isYuYue"
                >
                  <span>{{item.label}}</span>
                  <span>不可预约</span>
                </p>


                <!-- </div> -->
              </div>
            </template>
            <template v-if="!dateMinList.length">
              已下班
            </template>
          </div>
        </div>
        <div class="weui-dialog__ft dialog_bot_btn">
          <a @click="commit" class="weui-dialog__btn weui-dialog__btn_primary">确认</a>
        </div>
      </div>
    </div>
<!--    <getTime ref="getTime" @getDate="getDateFun"></getTime>-->
  </div>
</template>

<script>
import card from '@/components/card'
import * as appId from "@/utils/util"
import {status} from "@/utils/options"
 import {getTIme} from "@/utils/util"

export default {
  data () {
    return {
       pageNo:1,
        pageSize:10,
        result:[],
        resultList:[],
      phone:"",
      userInfo:{},


      timeShow:false,
      isClick:"09:00",//时分
      date:"",//月日

      dateList:[],
      id:"",
      dateToday:"",
      week:['周日','周一','周二','周三','周四','周五','周六'],
      startTime:"",
      endTime:"",
      times:"",
      EndMinute:0,
      itemData:{},
      noYuYue:[],
      dateMinList:[{
        isClick:false
      }]
    }
  },

  components: {
    card,

  },
 onPullDownRefresh(){
     console.log('down')
      if(this.result.length){
     this.pageNo++;
    }

     this.getDetail()

  },
   onShow(){
       wx.setNavigationBarTitle({
       title: "我的预约"
     })
     this.userInfo =wx.getStorageSync('userInfo')&&JSON.parse(wx.getStorageSync('userInfo'))
    if(this.userInfo) {
      this.phone=this.userInfo.mobileNo;
      this.getDetail()


    }else{
      wx.showToast({
        title:'请先登录',
        icon: 'none',
        duration: 2000
      })
    }

  },
  methods: {
    // 选择时间
    getTimeYu(id,date){
      return new Promise((relative)=>{
        this.$http.request({
          method: "post",
          url: "/v1.0/appletAppoint/appletAppointTime",
          body: {
            suffid:id,
            scheduledTime:date,
          }
        }).then((data)=>{
          if(data.code==0){
            relative(data.result||[]);
          }
        })
      })

    },
    close(){
      this.timeShow=false;
      this.dateList=[]
      this.dateMinList=[{
        isClick:false
      }]
    },
    changeMouse(data){
      let mouse=data/60;
    },
    initTime(time,endMinute,id){
      this.id=id;
      this.timeShow=true;

      if(endMinute){
        this.EndMinute=(endMinute/60).toFixed(1);
      }else{
        this.EndMinute=(30/60).toFixed(1);
      }
      if(time){
        this.startTime=Number(time.split('至')[0].split(':')[0]);
        this.endTIme=Number(time.split('至')[1].split(':')[0])-this.EndMinute;
      }else{
        this.startTime=10;
        this.endTIme=22;
      }


      console.log(this.startTime,this.endTIme)
      this.dateList=[]
      this.dateMinList=[{
        isClick:false
      }]
      // tMonth,
      // tDate
      this.times=this.getTodyTime().tYear+'-'+this.getTodyTime().tMonth+'-'+this.getTodyTime().tDate

      console.log(this.timeShow)
      this.getTime()
      this.todayDate(this.startTime, this.endTIme,id,this.times)
    },

    commit(){//确定时间
      if(this.isClick){
        let year= new Date().getFullYear();
        console.log(year,this.date,this.isClick)
        let date=year+'-'+this.date+' '+this.isClick
        this.timeShow=false;
        this.getDateFun(date)
        // this.time=date+':00';
        // this.$emit('getDate',date)
      }

    },
    handleFruitChange(val){
      this.isClick=val.target.value;
      // let arr=this.dateMinList.filter((item)=>{
      //   return item.label==this.isClick;
      // })

      this.dateMinList.forEach((a,i)=>{
        a.isClick=false;
        if(a.label==this.isClick){
          a.isClick=true;
        }
      })

      console.log(val)
    },
    // onChange(val){
    //     val.isClick=!val.isClick;
    //   console.log(val)
    // },
    changeDate(item){
      console.log(item)

      this.isClick="9:00";
      this.dateToday=item.date;
      // this.getTimeYu()
      let year="";
      if(this.getTodyTime().tMonth==12&&item.value.split('-')[0]=='01'){
        year=this.getTodyTime().tYear+1;
      }else{
        year=this.getTodyTime().tYear;
      }
      this.todayDate(this.startTime, this.endTIme,this.id,year+'-'+item.value)
      this.dateList.forEach((a,i)=>{
        a.isClick=false;
        a.isCurrent=false
      })
      if(!item.isCurrent){
        item.isCurrent=true;
      }
      this.date=item.value;

    },
    todayDate(a,b,id,times){
      let arr=[];
      // console.log(this.dateToday)
      this.getTimeYu(id,times).then((data)=>{
        if(this.dateToday.indexOf('今')!=-1){
          let house=new Date().getHours();
          let min=new Date().getMinutes();
          // console.log(this.endTime)
          if(house>=b){//超过23点
            this.dateMinList=[];
          }else if(house>=a){//大于9点
            if(min>=30){
              for(var i=house+1;i<b;i+=0.5){
                let obj={};
                obj.label=parseInt(i)+':'+this.isFloat((i-parseInt(i))*60)
                obj.isClick=""
                arr.push(obj)
                // obj.label=
              }
              this.dateMinList=arr;
            }else{
              for(var i=house+0.5;i<b;i+=0.5){
                let obj={};
                obj.label=this.add0(parseInt(i))+':'+this.isFloat((i-parseInt(i))*60)
                obj.isClick=""
                arr.push(obj)
                // obj.label=
              }
              this.dateMinList=arr;
            }

          }else{//小于9点
            if(min>=30){
              for(var i=a;i<b;i+=0.5){
                let obj={};
                obj.label=parseInt(i)+':'+this.isFloat((i-parseInt(i))*60)
                obj.isClick=""
                arr.push(obj)
                // obj.label=
              }
              this.dateMinList=arr;
            }
          }

        }else{
          for(var i=a;i<b;i+=0.5){
            let obj={};
            obj.label=this.add0(parseInt(i))+':'+this.isFloat((i-parseInt(i))*60)
            obj.isClick=""
            arr.push(obj)
            // obj.label=
          }
          this.dateMinList=arr;
        }

        // console.log(this.dateMinList)


        let arrs=data.map((item)=>{
          return this.changeHaomiaoDate(item.reserveTime)
        })
        //console.log(arrs)
        this.dateMinList.forEach((a,i)=>{
          a.isYuYue=true;
          arr.forEach((m,b)=>{
            if(a.label==m){
              a.isYuYue=false;
            }
          })

        })
        // for(let i=0;i<this.dateMinList.length;i++){

        //   // arr.forEach((a,b)=>{
        //   //   if(this.dateMinList[i].label=='15:00'){
        //   //      this.dateMinList[i].isYuYue=false;
        //   //   }
        //   // })
        // }
        console.log(this.dateMinList)

      })


    },
    changeHaomiaoDate(time){
      let date=new Date(time);
      let mouth=this.add0(date.getHours());
      let tDate = this.add0(date.getMinutes());
      console.log(mouth+':'+tDate)
      return mouth+':'+tDate;

    },
    isFloat(num){
      if(num==0){
        return '00'
      }else{
        return num
      }
    },
    getTodyTime(){
      var today = new Date();
      var tYear = today.getFullYear();
      var tMonth = today.getMonth();
      var tDate = today.getDate();
      tMonth = this.add0(tMonth + 1);

      tDate = this.add0(tDate);
      return {
        tYear,
        tMonth,
        tDate
      }
    },
    getDate(day){
      var today = new Date();

      var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
      today.setTime(targetday_milliseconds); //注意，这行是关键代码
      var tYear = today.getFullYear();
      var tMonth = today.getMonth();
      var tDate = today.getDate();
      tMonth = this.add0(tMonth + 1);
      tDate = this.add0(tDate);
      var dateWeek=today.getDay()
      var week=this.week[dateWeek];
      if(day==0){
        return {

          label:`今天(${week})`,
          value:tMonth+"-"+tDate

        }
      }else if(day==1){
        return {

          label:`明天(${week})`,
          value:tMonth+"-"+tDate

        }
      }else if(day==2){
        return{

          label:`后天(${week})`,
          value:tMonth+"-"+tDate

        }
      }else{
        return {
          label:tMonth+"-"+tDate,
          value:tMonth+"-"+tDate
        }
      }


    },

    getTime(){
      for(var i=0;i<6;i++){
        let obj={};
        // this.dateList[i]=this.getDate(i)
        obj.date=this.getDate(i).label
        obj.value=this.getDate(i).value
        if(i==0){
          this.date=obj.value;
          this.dateToday=obj.date;
          obj.isCurrent=true;
        }else{
          obj.isCurrent=false;
        }

        this.dateList.push(obj)
      }


    },
    add0(str){
      if(str<=9){
        return '0'+str;
      }  else{
        return str;
      }
    },
    showMulLinkageTwoPicker() {
      this.$refs.mpPicker.show();
    },
    onConfirm(e) {
      console.log(e);
    },
    // onChange(e) {
    //   console.log(e);
    // },
    onCancel(e) {
      console.log(e);
    },
    // 选择时间结束
    cancle(item){
      let that=this;
      wx.showModal({
        title: '取消提示',
        content: '确定取消预约?',
        success (res) {
          if (res.confirm) {
            wx.request({
              url: 'https://xcx.saas.apis.huidianzhang.com:8080/hdz-apprest/v1.0/appletOperat/appletAppointCancel', //仅为示例，并非真实的接口地址
              data: {
                "phone":that.phone,
                "appid":appId.appId,
                "userId":that.userInfo.baseUserId,
                "productId":item.id,
                "scheduledTime":item.reserveTime
              },
              method:'post',
              header: {
                'content-type': 'application/json' // 默认值
              },
              success (data) {
                if(data.data.code==0){
                  wx.showToast({
                    title: '取消成功',
                    icon: 'success',
                    duration: 2000
                  })
                  that.getDetail()
                }else{
                  wx.showToast({
                    title: `${data.data.message}`,
                    icon: 'success',
                    duration: 2000
                  })
                }
              }
            })
            // that.$http.request({
            //              method:"post",
            //              url:"/v1.0/appletOperat/appletAppointUpdate",
            //              body:{
            //                "phone":that.phone,
            //                "appid":appId.appId,
            //                "userId":that.userInfo.baseUserId,
            //                "productId":item.id,
            //                "scheduledTime":item.reserveTime
            //
            //      }
            //    }).then((data)=>{
            //      if(data.code==0){
            //          wx.showToast({
            //          title: '取消成功',
            //          icon: 'success',
            //          duration: 2000
            //        })
            //        that.getDetail()
            //      }else{
            //          wx.showToast({
            //          title: `${data.message}`,
            //          icon: 'success',
            //          duration: 2000
            //        })
            //      }
            //    })
          } else if (res.cancel) {

          }
        }
      })

    },
    getDateFun(val){
      console.log(this.itemData)
       let that=this;
      this.$http.request({
                   method:"post",
                   url:"/v1.0/appletOperat/appletAppointUpdate",
                   body:{
                     "phone":that.phone,
                     "appid":appId.appId,
                     "userId":that.userInfo.baseUserId,
                     "productId":this.itemData.id,
                     "scheduledTime":val+':00'
           }
         }).then((data)=>{
            if(data.code==0){
              wx.showToast({
                title: '修改成功',
                icon: 'success',
                duration: 2000,
                success:()=>{
                   that.getDetail()
                }
              })

            }
         })
    },
    changeTime(item){
      console.log(item)
      this.itemData=item;
      this.id=item.id;
      this.initTime(item.businessHours,item.endMinute,item.stuff.id)
      // this.$refs.getTime.init()

    },
    getDetail(){
       let that=this;
       this.$http.request({
                    method:"post",
                    url:"/v1.0/appletLogin/myAppointList",
                    body:{
                      "phone":that.phone,
                      "appid":appId.appId,
                      "pageNo":that.pageNo,
                      "pageSize":that.pageSize,
            }
          }).then((data)=>{
              if(data.code==0){
              that.result=data.result;
               if (that.pageNo > 1) {
              that.resultList.push(...data.result)
                console.log(that.resultList)
              }else{
                that.resultList=data.result;
              }
              console.log(status)
              that.resultList.forEach((a,i)=>{
                a.reserveTime=getTIme(a.reserveTime)
                 let arr=status.filter((item)=>{
                   return item.value==a.status;
                 })
                 a.statusLabel=arr[0]&&arr[0].label
              })
             // console.log(that.resultList)
               if(!data.length){
               wx.stopPullDownRefresh();
            //    wx.showToast({
            //   title: '暂无更多数据',
            //   icon: 'none',
            //   duration: 2000
            // })
            }

            }else{
               wx.showToast({
              title: `${data.message}`,
              icon: 'none',
              duration: 2000
            })
            }
          })
    },
    bindViewTap () {
      const url = '../logs/main'
      if (mpvuePlatform === 'wx') {
        mpvue.switchTab({ url })
      } else {
        mpvue.navigateTo({ url })
      }
    }
  },

  created () {
    // let app = getApp()
  }
}
</script>

<style scoped>
  /*时间*/
  .getTIme .radio-group{
    width: 100%;
  }
  .dialog_bot_con{
    text-align: left;
    padding: 0px;
  }
  .dialog_bot_btn .weui-dialog__btn_primary{
    margin: 0.6em 2em;
    background: #FF787E;
    border-radius: 1.2em;
    color: #fff;
    height: 2.4em;
  }
  .date{
    background: #f8f8f8;
    width: 8em;
    color: #333;
    font-size: 1em;
  }
  .dialog_bot_title{
    height: 2.6em;
    line-height: 2.6em;
    border-bottom: 1px #eee solid;
    padding: 0px;
    text-align: left;
  }
  .dialog_bot{
    min-width: 100%;
    bottom: 0px;
    left: 0px;
    right: 0px;
    top: auto;
    z-index: 999999;
    -webkit-transform:translate(0%,0%);
    transform:translate(0%,0%);
  }
  .time{
    padding: 0.6em;
  }
  .time .current{
    color: #FF787E;
  }
  .date ul li.current{
    background: #fff;
  }
  .date ul li{
    height: 2.4em;
    line-height: 2.4em;
    text-align: center;
  }
  .date ul li.current{
    background: #fff;
  }
.s_pic{
  width: 5.6em;
  height: 5.6em;
  border-radius: 0.3em;
  margin-right: 0.6em;
}
.s_info div{
  font-size: 0.8em;
  color: #333;
  line-height: 1.6em;
}
.btngroup{
  text-align: right;
  padding-top: 0.6em;
}
.btngroup a{
  display: inline-block;
  margin-left: 0.4em;
  width: 6.4em;
  height: 2.2em;
  background: #fff;
  border:1px #aaa solid;
  color: #666;
  text-align: center;
  line-height: 2.2em;
  border-radius: 1.1em;
  font-size: 0.9em;
}
</style>
